<?php
namespace app\web\controller;

use app\model\Record; 
use app\model\Util; 
use app\model\Theme; 

class Fake extends Base
{
    public function Fake()
    {
global $_G, $_P;
$system = $_G['system'];
$_G['page']['title'] = '马甲列表 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew($_G['mpid']);
}
if(empty($themeid)){
	return_msg('还没有创建活动,请联系管理员');
}
$config = Theme::getConfig($themeid);
$id = intval($_P['id']);
$do = 'fake';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));
if($op == 'import'){
	$filename = $_FILES['file']['name'];
	$tmp_name = $_FILES['file']['tmp_name'];
	if (empty ($filename)) {
		return_tips ('请选择要导入的Excel文件');
	}
	$excefile = 'file';
	$data = Util::importExcel($excefile);
	if(empty($data)){
		return_tips ('没有数据！');
	}
	$addtime = TIMESTAMP;
	foreach($data as $index =>$row){
		$data = array(
				'nickname' => $row[0],
				'avatar'   => $row[1],
				'uniacid'  => $_G['mpid'],
                'type'     => -1,
				'themeid'  => $themeid,
		);
        $id = Fake::save($data);
		if(empty($id)){
			return_tips ('导入错误！');
		}
	}
	return_tips ( '导入成功', $url, 'success' );
	 
}


if($op == 'post') {
	if($id > 0) {
		$item = Fake::getById($id);
		if(empty($item)) {
			return_tips('不存在或已删除', $url, 'success');
		}
	}
	
	if(checksubmit('submit')) {
		if(empty($_P['nickname']) || empty($_P['avatar'])){
			return_tips('信息不可为空');
		}
		$data = array(
				'nickname' => $_P['nickname'],
				'avatar'   => $_P['avatar'],
                'status'   => $_P['status'],
				);
		if ($id > 0) {
			Fake::update($id,$data);
		} else {
			$data ['uniacid'] = $_G['mpid'];
			$data ['themeid'] = $themeid;
            $data ['type'] = -1;
            $id = Fake::save($data);
		}
        $item = Fake::getById($id);
		if($_P['type'] > 0){
            if($item['type'] != -1){
                return_tips('该马甲已被使用');
            }
            if(!empty($item['groupid'])){
                return_tips('该马甲已被使用');
            }
		    if($_P['type'] == 1){
                if(empty($_P['groupid'])){
                    return_tips('请设置要加入的团长ID');
                }
                $record = Record::getById($_P['groupid']);
                if($record['type'] != 0){
                    return_tips('不是团长ID');
                }
                if($record['isfinish'] != 0){
                    return_tips('已经拼团成功');
                }

                $data = array(
                    'uniacid'  => $_G['mpid'],
                    'themeid'  => $themeid,
                    'nickname' => $_P['nickname'],
                    'avatar'   => $_P['avatar'],
                    'addtime'  => TIMESTAMP,
                    'fee'      => 0.00,
                    'status'   => 1,
                    'pid'      => $_P['groupid'],
                    'type'     => 1,
                    'uncode'   => $themeid.'-'.TIMESTAMP.rand(1000,1000000)
                );
                $recordid = Record::save($data);
                $count = Record::getAttendDetailNumByPId($_P['groupid']);
                $neednum = intval($config['maxcount']);
                if($count >= $neednum){
                    Record::update($_P['groupid'],array("isfinish"=>1));
                }
                Fake::update($id,array("type"=>1,"groupid"=>$_P['groupid']));
            }elseif ($_P['type'] == 2){
                $data = array(
                    'uniacid'  => $_G['mpid'],
                    'themeid'  => $themeid,
                    'nickname' => $_P['nickname'],
                    'avatar'   => $_P['avatar'],
                    'addtime'  => TIMESTAMP,
                    'fee'      => 0.00,
                    'status'   => 1,
                    'pid'      => 0,
                    'type'     => 0,
                    'uncode'   => $themeid.'-'.TIMESTAMP.rand(1000,1000000)
                );
                $recordid = Record::save($data);
                Fake::update($id,array("type"=>0,"groupid"=>$recordid));
            }

        }
		return_tips('设置成功',$url, 'success');
	}
}

if($op == 'display') {
	$params[':uniacid'] = $_G['mpid'];
	$params[':themeid'] = $themeid;
	
	$pindex = max(1, intval($_P['page']));
	$psize = 50;

	$sql = "SELECT COUNT(*) FROM " . tablename(t_fake) . " as g WHERE g.uniacid = :uniacid and g.themeid = :themeid";
	$total = db_fetchcolumn($sql, $params);
	
	
	$sql = "SELECT g.* FROM ". tablename(t_fake) . " as g 
				WHERE g.uniacid = :uniacid and g.themeid = :themeid
						 ORDER BY g.id desc LIMIT ".($pindex - 1) * $psize.','.$psize;
	$list = db_select($sql, $params);

	$pager = pagination($total, $pindex, $psize);

}


if($op == 'finish') {
	$finish = intval($_P['finish']);
	$item = db_find('SELECT * FROM ' . tablename(t_fake) . '
				WHERE uniacid = :uniacid AND id = :id', array(':uniacid' => $_G['mpid'], ':id' => $id));
	if($finish > 0){
		
		$min = $system['hbmin'] * 10;
		$max = $system['hbmax'] * 10;
		$randomfee = intval(mt_rand($min,$max));
		$randomfee = floatval($randomfee/10);
		$desc = $system['fcardtitle'].'赏金';
		$ordersn = getMillisecond();
		$data = array(
				'uniacid'    => $_G['mpid'],
				'ordersn'    => $ordersn,
				'type'       => 1,
				'openid'     => $item['openid'],
				'uid'        => 0,
				'addtime'    => TIMESTAMP,
				'fee'        => $randomfee,
				'uniquekey'  => $ordersn.'-'.$item['openid'].'-'.TIMESTAMP,
				'ip'         => $_G['clientip'],
				'status'     => 0,
				'fakeid'     => $id,
		);
		if(!empty($item['openid'])){
			$r = $insertid = db_insert(t_comm, $data);
			if(!empty($r)){
				$commid = $insertid;
				$txresult = transfer($item['openid'],$randomfee,$ordersn,$desc,$system);
				if($txresult['code'] == 0){
					$status = 1;
					$msg = '成功';
				}else{
					$status = 0;
					$msg = $txresult['return_tips'];
				}
				db_update(t_comm,array("status"=>$status,"msg"=>$msg), array('id' => $commid));
				 
			}else{
				return_tips(error(1, '数据插入失败'), '', 'ajax');
			}
		}else{
			$data['status'] = 1;
			$data['msg'] = 成功;
			$r = $insertid = db_insert(t_comm, $data);
		}
		db_update ( t_fake, array("fee"=>$randomfee,'finish'=>$finish), array ('id' => $id) );
		$fdata = array(
				"finish"=>1,
				"left"  =>mt_rand(0,3),
				"card1" =>mt_rand(1,4),
				"card2" =>mt_rand(1,4),
				"card3" =>mt_rand(1,4),
				"card4" =>mt_rand(1,4),
				"card5" =>mt_rand(1,4),
		);
		db_update ( t_fans, $fdata, array ('fakeid' => $id) );
	}
	return_tips(error(0, ''), '', 'ajax');
}

if($op == 'status') {
	$status = intval($_P['status']);
	$state = db_update(t_fake, array('status' => $status), array('uniacid' => $_G['mpid'], 'id' => $id));
	return_tips(error(0, ''), '', 'ajax');
}

if($op == 'delete') {
	db_delete(t_fake, array('uniacid' => $_G['mpid'],'id' => $id));
	return_tips('删除成功', $url, 'success');
}


$return_clicent = get_defined_vars();
return view('/fake' , $return_clicent);
}
}